package com.lh.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lh.enums.CommentLevel;
import com.lh.mapper.ItemsCommentsExtMapper;
import com.lh.mapper.ItemsCommentsMapper;
import com.lh.mapper.ItemsExtMapper;
import com.lh.mapper.ItemsImgMapper;
import com.lh.mapper.ItemsMapper;
import com.lh.mapper.ItemsParamMapper;
import com.lh.mapper.ItemsSpecMapper;
import com.lh.pojo.Items;
import com.lh.pojo.ItemsComments;
import com.lh.pojo.ItemsImg;
import com.lh.pojo.ItemsParam;
import com.lh.pojo.ItemsSpec;
import com.lh.pojo.vo.CommentLevelVO;
import com.lh.pojo.vo.ItemCommentVO;
import com.lh.pojo.vo.SearchItemsVO;
import com.lh.pojo.vo.ShopCartVO;
import com.lh.service.ItemService;
import com.lh.utils.DesensitizationUtil;
import com.lh.utils.PagedGridResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: foodie-dev
 * @description:
 * @author: LH
 * @create: 2022-05-06 17:26
 **/
@Service
public class ItemServiceImpl implements ItemService {

    @Autowired
    private ItemsMapper itemsMapper;
    @Autowired
    private ItemsImgMapper itemsImgMapper;
    @Autowired
    private ItemsSpecMapper itemsSpecMapper;
    @Autowired
    private ItemsParamMapper itemsParamMapper;
    @Autowired
    private ItemsCommentsMapper itemsCommentsMapper;
    @Autowired
    private ItemsCommentsExtMapper itemsCommentsExtMapper;
    @Autowired
    private ItemsExtMapper itemsExtMapper;

    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public Items queryItem(String itemId) {
        return itemsMapper.selectByPrimaryKey(itemId);
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public List<ItemsImg> queryItemImgList(String itemId) {
        Example example = new Example(ItemsImg.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("itemId", itemId);
        return itemsImgMapper.selectByExample(example);
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public List<ItemsSpec> queryItemSpecList(String itemId) {
        Example example = new Example(ItemsSpec.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("itemId", itemId);
        return itemsSpecMapper.selectByExample(example);
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public ItemsParam queryItemParam(String itemId) {
        Example example = new Example(ItemsParam.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("itemId", itemId);
        return itemsParamMapper.selectOneByExample(example);
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public CommentLevelVO getCommentLevelNum(String itemId) {

        CommentLevelVO commentLevelVO = new CommentLevelVO();

        Example example_good = new Example(ItemsComments.class);
        Example.Criteria criteria_good = example_good.createCriteria();
        criteria_good.andEqualTo("itemId", itemId);
        criteria_good.andEqualTo("commentLevel", CommentLevel.GOOD.getType());
        int good = itemsCommentsMapper.selectCountByExample(example_good);
        commentLevelVO.setGoodCounts(good);

        Example example_bad = new Example(ItemsComments.class);
        Example.Criteria criteria_bad = example_bad.createCriteria();
        criteria_bad.andEqualTo("itemId", itemId);
        criteria_bad.andEqualTo("commentLevel", CommentLevel.BAD.getType());
        int bad = itemsCommentsMapper.selectCountByExample(example_bad);
        commentLevelVO.setBadCounts(bad);

        Example example_normal = new Example(ItemsComments.class);
        Example.Criteria criteria_normal = example_normal.createCriteria();
        criteria_normal.andEqualTo("itemId", itemId);
        criteria_normal.andEqualTo("commentLevel", CommentLevel.NORMAL.getType());
        int normal = itemsCommentsMapper.selectCountByExample(example_normal);
        commentLevelVO.setNormalCounts(normal);

        Example example = new Example(ItemsComments.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("itemId", itemId);
        int total = itemsCommentsMapper.selectCountByExample(example);
        commentLevelVO.setTotalCounts(total);

        return commentLevelVO;
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public PagedGridResult getComments(String itemId, Integer level, Integer page, Integer pageSize) {

        Map<String, Object> map = new HashMap<>();
        map.put("itemId", itemId);
        map.put("commentLevel", level);

        /**
         * page: 第几页
         * pageSize: 每页显示条数
         */
        PageHelper.startPage(page, pageSize);

        List<ItemCommentVO> list = itemsCommentsExtMapper.getComments(map);
        if (!CollectionUtils.isEmpty(list)){
            list.stream().forEach(item->{
                item.setNickname(DesensitizationUtil.commonDisplay(item.getNickname()));
            });
        }

        PagedGridResult pageData = getPageData(list, page);
        return pageData;
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public PagedGridResult searchItemsByKeywords(String keywords, String sort, Integer page, Integer pageSize) {

        Map<String, Object> map = new HashMap<>();
        map.put("keywords", keywords);
        map.put("sort", sort);

        PageHelper.startPage(page, pageSize);

        List<SearchItemsVO> list = itemsExtMapper.searchItemsByKeywords(map);
        PagedGridResult pageData = getPageData(list, page);

        return pageData;
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public PagedGridResult searchItemsByCatId(Integer catId, String sort, Integer page, Integer pageSize) {
        Map<String, Object> map = new HashMap<>();
        map.put("catId", catId);
        map.put("sort", sort);

        PageHelper.startPage(page, pageSize);

        List<SearchItemsVO> list = itemsExtMapper.searchItemsByCatId(map);
        PagedGridResult pageData = getPageData(list, page);

        return pageData;
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public List<ShopCartVO> refreshShopCart(List<String> specIdList) {

        List<ShopCartVO> shopCartVOList = itemsExtMapper.refreshShopCart(specIdList);
        return shopCartVOList;
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public ItemsSpec getItemsSpecById(String id) {
        ItemsSpec itemsSpec = itemsSpecMapper.selectByPrimaryKey(id);

        if (itemsSpec == null){
        throw new RuntimeException("商品规格查询失败!");
        }
        return itemsSpec;
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public ItemsImg queryItemImgByItemIdAndIsMain(String itemId) {

        //设置主图
        Integer isMain = 1;

        ItemsImg searchItemsImg = new ItemsImg();
        searchItemsImg.setItemId(itemId);
        searchItemsImg.setIsMain(isMain);
        ItemsImg itemsImg = itemsImgMapper.selectOne(searchItemsImg);
        if (itemId == null){
            throw new RuntimeException("查询商品主图失败!");
        }

        return itemsImg;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void decreaseItemSpecStock(String specId, Integer buyCounts) {
        // synchronized 不推荐使用，集群下无用，性能低下
        // 锁数据库: 不推荐，导致数据库性能低下
        // 分布式锁 zookeeper redis

        // lockUtil.getLock(); -- 加锁

        // 1. 查询库存
//        int stock = 10;

        // 2. 判断库存，是否能够减少到0以下
//        if (stock - buyCounts < 0) {
        // 提示用户库存不够
//            10 - 3 -3 - 5 = -1
//        }

        // lockUtil.unLock(); -- 解锁

        int result = itemsExtMapper.decreaseItemSpecStock(specId, buyCounts);
        if (result != 1) {
            throw new RuntimeException("订单创建失败，原因：库存不足!");
        }
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    public PagedGridResult getPageData(List<?> list, Integer page){
        PageInfo<?> pageList = new PageInfo<>(list);
        PagedGridResult grid = new PagedGridResult();
        grid.setPage(page);
        grid.setRows(list);
        grid.setTotal(pageList.getPages());
        grid.setRecords(pageList.getTotal());
        return grid;
    }
}
